package org.linlinjava.litemall.admin.service2;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.admin.service.ASettlementCenterService;
import org.linlinjava.litemall.admin.web2.order.req.OReq;
import org.linlinjava.litemall.admin.web2.order.req.OReq2;
import org.linlinjava.litemall.admin.web2.order.req.OReq3;
import org.linlinjava.litemall.admin.web2.order.resp.*;
import org.linlinjava.litemall.core.util.DateTimeUtil;
import org.linlinjava.litemall.core.util.R;
import org.linlinjava.litemall.core.util.Util;
import org.linlinjava.litemall.db.dao.TCouponMapper;
import org.linlinjava.litemall.db.dao.TOrderItemMapper;
import org.linlinjava.litemall.db.dao.TUserCouponMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.enumeration.Const;
import org.linlinjava.litemall.db.util.Str;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class AOrderService extends ABaseService {

    private static Logger log = LoggerFactory.getLogger(AOrderService.class);


    private <T extends OResp> List<T> list0(Class clazz, OReq req, Integer... status) {
        List<Integer> statusList = Util.aList(status.length);
        for (Integer s : status) {
            statusList.add(s);
        }
        initPage(req);
        if (req.getOrderType() != null && req.getOrderType() == -1)
            req.setOrderType(null);
        PageHelper.startPage(req.getPage(), req.getSize());
        List<TOrder> orderList = orderMapper.selectByExample(TOrderExample.newAndCreateCriteria()
                .when(status != null, c -> c.andOrderStatusIn(statusList))
                .when(req.getShopId() != null, c -> c.andShopIdEqualTo(req.getShopId()))
                .when(req.getPickUpId() != null, c -> c.andGoodsAddressIdEqualTo(req.getPickUpId()))
                .when(req.getOrderType() != null, c -> c.andOrderTypeEqualTo(req.getOrderType()))
                .when(!Str.isEmpty(req.getBeginDate()), c -> c.andCreatedTimeGreaterThanOrEqualTo(DateTimeUtil.formatYYYY_MM_DD(req.getBeginDate())))
                .when(!Str.isEmpty(req.getEndDate()), c -> c.andCreatedTimeLessThan(DateTimeUtil.formatYYYY_MM_DD(req.getEndDate())))
                .when(!Str.isEmpty(req.getTransNo()), c -> c.andTransNoEqualTo(req.getTransNo()))
                .when(!Str.isEmpty(req.getPhone()), c -> c.andHarvesterPhoneEqualTo(req.getPhone()))
                .when(!Str.isEmpty(req.getName()), c -> c.andHarvesterNameLike(Str.toLike(req.getName())))
                .example().orderBy("id desc")
        );
        //查询出来，封装成公共vo返回
        List<T> list = Util.pageList(orderList);
        for (TOrder o : orderList) {
            try {
                T t = (T) clazz.newInstance();
                t.pushOrder(o);
                t.pushOrderItems(orderItemMapper.selectByExample(TOrderItemExample.newAndCreateCriteria().andOrderIdEqualTo(o.getId()).example()));
                t.pushUser(findUserInfoByUser2Id(o.getuId()));
                list.add(t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 待付款
     *
     * @return
     */
    public Object list1(OReq req) {
        List<OResp1> list = list0(OResp1.class, req, Const.ORDER_STATUS_TYPE.NO_PAYMENT);
        return R.okList(list);
    }

    /**
     * 已关闭订单
     *
     * @return
     */
    public Object list2(OReq req) {
        log.info("查询[超时未付款、超时未收货]");
        List<OResp2> list = list0(OResp2.class, req, Const.ORDER_STATUS_TYPE.EXPIRE_RECEIPT, Const.ORDER_STATUS_TYPE.EXPIRE);
        return R.okList(list);
    }

    /**
     * 已完成订单
     *
     * @return
     */
    public Object list3(OReq req) {
        log.info("查询[待分享、已完成]");
        List<OResp3> list = list0(OResp3.class, req, Const.ORDER_STATUS_TYPE.FINISHED);
        return R.okList(list);
    }

    /**
     * 待派送订单
     *
     * @return
     */
    public Object list4(OReq req) {
        log.info("查询[待发货]");
        List<OResp4> list = list0(OResp4.class, req, Const.ORDER_STATUS_TYPE.NO_SEND, Const.ORDER_STATUS_TYPE.NO_PICK_UP);
        return R.okList(list);
    }

    /**
     * 已发货订单
     *
     * @return
     */
    public Object list5(OReq req) {
        log.info("查询[待发货]");
        List<OResp5> list = list0(OResp5.class, req, Const.ORDER_STATUS_TYPE.NO_PICK_UP);
        return R.okList(list);
    }


    /**
     * 已支付未成团
     *
     * @return
     */
    public Object list6(OReq2 req) {
        log.info("查询[已支付未成团]");
        initPage(req);
        PageHelper.startPage(req.getPage(), req.getSize());
        //先查出团订单
        List<TGroupOrder> groupOrders = groupOrderMapper.selectByExample(
                TGroupOrderExample.newAndCreateCriteria()
                        .when(!Str.isEmpty(req.getTransNo()), c -> c.andTransNoEqualTo(req.getTransNo()))
                        .when(!Str.isEmpty(req.getBeginDate()), c -> c.andCreatedTimeGreaterThanOrEqualTo(DateTimeUtil.formatYYYY_MM_DD(req.getBeginDate())))
                        .when(!Str.isEmpty(req.getEndDate()), c -> c.andCreatedTimeLessThan(DateTimeUtil.formatYYYY_MM_DD(req.getEndDate())))
                        .andStatusEqualTo(Const.GROUP_ORDER_STATUS_TYPE.OPEN_NO_FULL).example());
        List<OResp6> list = Util.pageList(groupOrders);
        groupOrders.forEach(g -> {
            OResp6 vo = new OResp6();
            vo.pushOrder(g);
            vo.pushUser(findUserById(g.getLeaderId()));
            vo.pushGoods(findGoodsById(g.getGoodsId()));
            list.add(vo);
        });
        return R.okList(list);
    }

    /**
     * 订单详情
     *
     * @param oId
     * @return
     */
    public Object orderDetail(Integer oId) {
        log.info("查看订单详情");
        TOrder order = orderMapper.selectByPrimaryKey(oId);
        OResp7 vo = new OResp7();
        vo.pushOrder(order);

        int totalCount = 0;
        List<TOrderItem> orderItems = orderItemMapper.selectByExample(TOrderItemExample.newAndCreateCriteria().andOrderIdEqualTo(oId).example());
        for (TOrderItem i : orderItems) {
            totalCount += i.getGoodsNum();
            Dto1 dto = new Dto1(findGoodsById(i.getGoodsId()), i.getGoodsNum());
            vo.getItems().add(dto);
        }
        vo.setTotalCount(totalCount + "");

        //下单会员
        TUser2 user = findUserById(order.getuId());
        vo.setMemberName(user.getName());

        //优惠
        Integer couponId = order.getCouponId();
        vo.setCouponAmount("0");
        if (couponId != null) {
            TUserCoupon tUserCoupon = userCouponMapper.selectByPrimaryKey(couponId);
            if (tUserCoupon != null) {
                TCoupon currentUsedCoupon = couponMapper.selectByPrimaryKey(tUserCoupon.getCouponId());  //当前使用的优惠券类型
                if (currentUsedCoupon != null) {
                    vo.setCouponAmount(currentUsedCoupon.getAmount().toString());
                }
            }
        }

        //提货点
        if (order.getGoodsAddressId() != null) {
            TShop shop = shopMapper.selectByPrimaryKey(order.getGoodsAddressId());
            vo.setPickupShopInfo(shop.getShopName());
        }
        if (order.getPickupTime() != null)
            vo.setPickupTime(DateTimeUtil.format.format(order.getPickupTime()));
        return R.ok(vo);
    }

    /**
     * 订单配送
     *
     * @param req
     * @return
     */
    public Object sendOrder(OReq3 req) {
        Integer[] ids = req.getoIds();
        List<Integer> list = Arrays.asList(ids);
        List<TOrder> orders = orderMapper.selectByExample(TOrderExample.newAndCreateCriteria().andIdIn(list).example());
        for (TOrder order : orders) {
            if (order.getSendType() == Const.SEND_TYPE.SELF_MENTION) {
                log.info("订单(自提)[{}]状态从[待发货]->[已完成]", order.getTransNo());
                order.setOrderStatus(Const.ORDER_STATUS_TYPE.FINISHED);
            }
            if (order.getSendType() == Const.SEND_TYPE.NORMAL) {
                log.info("订单(普通配送)[{}]状态从[待发货]->[已完成]", order.getTransNo());
                order.setOrderStatus(Const.ORDER_STATUS_TYPE.FINISHED);
            }
            if (order.getSendType() == Const.SEND_TYPE.TIMELY) {
                log.info("订单(及时达配送)[{}]状态从[待发货]->[已完成]", order.getTransNo());
                order.setOrderStatus(Const.ORDER_STATUS_TYPE.FINISHED);
            }
            order.setOperator("后台管理员");
            order.setPickupTime(LocalDateTime.now());
            order.setCloseReason("后台操作发货，完成订单");
            orderMapper.updateByPrimaryKeySelective(order);
            settlementCenterService.settlement(order);
        }
        return R.ok("发货成功");
    }

    private void initPage(OReq2 req) {
        if (req.getPage() == null)
            req.setPage(1);
        if (req.getSize() == null)
            req.setSize(10);
    }

    @Autowired
    private ASettlementCenterService settlementCenterService;
    @Autowired
    private TOrderItemMapper orderItemMapper;
    @Autowired
    private TCouponMapper couponMapper;
    @Autowired
    private TUserCouponMapper userCouponMapper;


}
